import datetime
import database


def book_check_out(member_id, book_id):
    # find the loan history
    member_bold_books = database.book_charge(member_id)
    # check the book want borrow is valid or not
    book_is_valid = database.book_check_out(book_id)
    # the book is valid and the people hold no overdue book
    if member_bold_books is None:
        if book_is_valid == "0":
            # get check out book time
            checkout_date = datetime.date.today()
            # update the book status
            database.book_update(book_id, member_id)
            # insert one new book loan history
            database.insert_loan_history(book_id, checkout_date)
            return True
        else:
            return False
    else:
        loan_periods = member_bold_books[1]
        checkout_date = datetime.datetime.strptime(member_bold_books[0], "%Y-%m-%d")
        now = datetime.datetime.today()
        days = (now - checkout_date).days
        if days > loan_periods:
            return False
        else:
            if book_is_valid == "0":
                # get check out book time
                checkout_date = datetime.date.today()
                # update the book status
                database.book_update(book_id, member_id)
                # insert one new book loan history
                database.insert_loan_history(book_id, checkout_date)
                return True
            else:
                return False


if __name__ == "__main__":
    # test data member_id=oopp, book_id="1"
    # result is  oopp can not borrow any book because he hold oen overdue book
    book_check_out("oopp", "1")
